<template>
  <div class="login-page">
    <el-card>
      <template #header>黑马面经运营后台</template>
      <el-form autocomplete="off" label-width="60px" :model="user" :rules="rules" ref="form">
        <el-form-item label="账 号" prop="username">
          <el-input v-model="user.username" placeholder="输入用户名"></el-input>
        </el-form-item>

        <el-form-item label="密 码" prop="password">
          <el-input v-model="user.password" type="password" placeholder="输入用户密码"></el-input>
        </el-form-item>

        <el-form class="tc">
          <el-button type="primary" @click="login">登 录</el-button>
          <el-button>重 置</el-button>
        </el-form>
      </el-form>
    </el-card>
  </div>
</template>

<script>
// 导入封装的loginAPI
import { loginAPI } from '@/api/user'
export default {
  name: 'LoginIndex',
  data () {
    return {
      user: {
        username: 'admin',
        password: 'admin'
      },
      rules: {
        // 校验规则
        username: [
          { required: true, message: '请输入用户名', trigger: ['blur', 'change'] },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: ['blur', 'change'] }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: ['blur', 'change'] },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  methods: {
    login () {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          // 通过验证
          const res = await loginAPI(this.user)
          console.log(res)
          // 提示登录成功
          this.$message.success('登录成功')
          // 存储token到vuex
          this.$store.commit('user/updateToken', res.data.token)
          // 跳转到首页
          this.$router.push('/')
        } else {
          // 验证不通过，什么都不做，不要提交数据
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.login-page {
  min-height: 100vh;
  background: url(@/assets/login-bg.svg) no-repeat center / cover;
  display: flex;
  align-items: center;
  justify-content: space-around;
  .el-card {
    width: 420px;
    ::v-deep .el-card__header {
      height: 80px;
      background: rgba(114, 124, 245, 1);
      text-align: center;
      line-height: 40px;
      color: #fff;
      font-size: 18px;
    }
  }
  .el-form {
    padding: 0 20px;
  }
  .tc {
    text-align: center;
  }
}
</style>
